package drds.server.net.packet;

import java.nio.ByteBuffer;

import drds.server.buffer.ByteBufferList;
import drds.server.net.SessionContext$LifeCycle;

/**
 * From Server To Client, at the end of a series of Field Packets, and at the
 * end of a series of Data Packets.With prepared statements, EOF Packet can also
 * end parameter information, which we'll describe later.
 * 
 * <pre>
 * Bytes                 Name
 * -----                 ----
 * 1                     field_count, always = 0xfe
 * 2                     warning_count
 * 2                     Status Flags
 * 
 * @see http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#EOF_Packet
 * </pre>
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class EofPacket extends Packet {
	public static final byte FIELD_COUNT = (byte) 0xfe;

	public byte fieldCount = FIELD_COUNT;
	public int warningCount;
	public int status = 2;

	public void read(byte[] bytes) {
		BytesHolder bytesHolder = new BytesHolder(bytes);
		packetLength = bytesHolder.readInt3();
		packetId = bytesHolder.read();
		fieldCount = bytesHolder.read();
		warningCount = bytesHolder.readInt2();
		status = bytesHolder.readInt2();
	}

	@Override
	public ByteBuffer write(ByteBuffer byteBuffer, SessionContext$LifeCycle sessionContext, boolean writeSocketIfFull) {
		int size = computePacketSize();
		byteBuffer = sessionContext.checkWriteByteBuffer(byteBuffer, sessionContext.getPacketHeaderSize() + size, writeSocketIfFull);
		ByteBufferUtil.writeInt3(byteBuffer, size);
		byteBuffer.put(packetId);
		byteBuffer.put(fieldCount);
		ByteBufferUtil.writeInt2(byteBuffer, warningCount);
		ByteBufferUtil.writeInt2(byteBuffer, status);
		return byteBuffer;
	}

	@Override
	public int computePacketSize() {
		return 5;// 1+2+2;
	}

	public void write(ByteBufferList byteBufferList) {
		int size = computePacketSize();
		ByteBuffer byteBuffer = byteBufferList.checkWritingByteBufferCapacity(packetHeaderSize + size);
		ByteBufferUtil.writeInt3(byteBuffer, size);
		byteBuffer.put(packetId);
		byteBuffer.put(fieldCount);
		ByteBufferUtil.writeInt2(byteBuffer, warningCount);
		ByteBufferUtil.writeInt2(byteBuffer, status);
	}

}